package com.module.retrofit.callback;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

import com.module.retrofit.exception.ResponseException;
import com.module.retrofit.utils.NetUtil;
import com.module.retrofit.utils.ToastUtil;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @Author: dengqi
 * @CreateDate: 2020/9/23 16:10
 * @Description:
 */
public abstract class DialogObserver<T> implements Observer<T>, DialogInterface.OnDismissListener {

    private Disposable disposable;
    private AlertDialog dialog;
    private Context mContext;

    public DialogObserver(Context mContext){
        this.mContext = mContext;
        this.dialog = new AlertDialog.Builder(mContext).setMessage("加载中").create();
        this.dialog.setOnDismissListener(this);
        this.dialog.setOwnerActivity((Activity)mContext);
    }

    @Override
    public void onDismiss(DialogInterface dialogInterface) {
        destory();
    }


    @Override
    public void onSubscribe(Disposable d) {
        //先判断网络环境
        if(!NetUtil.isNetworkConnected(mContext)){
            d.dispose();
            ToastUtil.showToast("请连接网络");
            return;
        }
        dialog.show();
        disposable = d;
    }



    @Override
    public void onNext(final T t) {
        onSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
        if(e instanceof ResponseException){
            ResponseException responseException = (ResponseException) e;
            ToastUtil.showToast(responseException.getErrorMessage());
        }else{
            e.printStackTrace();
            ToastUtil.showToast(e.toString());
        }
        destory();
    }

    @Override
    public void onComplete() {
        destory();
    }

    /**
     * 对话框取消、请求异常、请求完成 三种情况取消订阅
     */
    private void destory(){
        if(dialog!=null && dialog.isShowing()){
            dialog.dismiss();
        }
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }



    public abstract void onSuccess(T result);

}